package store

import (
	"cms/core/cache"
	"cms/utils/convert"
	"fmt"
	"github.com/gomodule/redigo/redis"
	"github.com/sirupsen/logrus"
	"strings"
)

func GetAdminToken(token string) (string, error) {
	ca := cache.Redis.Get()
	defer ca.Close()

	str, err := redis.String(ca.Do("GET", "admin:login_token:" + token))
	if err != nil {
		return "", err
	}
	info := strings.Split(str, ":")
	if len(info) != 2 {
		return "", err
	}
	err = SetAdminToken(info[0], token, convert.StrToInt(info[1]))
	if err != nil {
		return "", err
	}

	return info[0], nil
}

func SetAdminToken(key string, token string, expire int) error {
	ca := cache.Redis.Get()
	defer ca.Close()

	token = "admin:login_token:" + token

	if _, err := ca.Do("SETEX", token, expire, fmt.Sprintf("%s:%d", key, expire)); err != nil {
		logrus.Errorf("redis set fail: %v", err.Error())
		return err
	}

	return nil
}

// RemoveAdminToken 删除token
func RemoveAdminToken(token string) error {
	ca := cache.Redis.Get()
	defer ca.Close()
	key := "admin:login_token:" + token
	if _, err := ca.Do("DEL", key); err != nil {
		return err
	}
	return nil
}
